﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using IoCNamed.UnityNameResolver;
using IoCNamed.Persistence;
using IoCNamed.UnityParamsResolver;

namespace IoCNamed
{
    class Program
    {
        static private object GetConfigValue(Type typeToBuild, string valueName)
        {
            switch (valueName)
            {
                case "DBConnectionString":
                    return "connection string";
                case "Filename":
                    return "datafile.xml";
                case "Persistence":
                    return "db";
            }

            return null;
        }

        static private string GetPersistenceImplementationName(Type typeToBuild)
        {
            return "db";
        }

        static void Main(string[] args)
        {
            IUnityContainer uc = new UnityContainer();

            uc.RegisterType<IPersistence, InMemoryPersistence>("none");
            uc.RegisterType<IPersistence, FilePersistence>("file");
            uc.RegisterType<IPersistence, FilePersistence>("bin-file");
            uc.RegisterType<IPersistence, DbPersistence>("db");
            uc.RegisterType<IPersistence, WsPersistence>("ws");

            uc.Configure<InjectedMembers>().ConfigureInjectionFor<FilePersistence>("file",
                new InjectionConstructor("datafile.xml", "xml"));
            uc.Configure<InjectedMembers>().ConfigureInjectionFor<FilePersistence>("bin-file",
                new InjectionConstructor("datafile.bin", "binary"));
            uc.Configure<InjectedMembers>().ConfigureInjectionFor<DbPersistence>("db",
                new InjectionConstructor(
                    new DelegatedInjectionValue<string>("DBConnectionString", GetConfigValue)));
            uc.Configure<InjectedMembers>().ConfigureInjectionFor<WsPersistence>("ws",
                new InjectionConstructor("http://localhost/", "save", "petrovich", "12345"));

            uc.AddNewExtension<NameResolverExtension>();
            uc.Configure<INameResolverExtensionConfigurator>().RegisterDelegatedName<IPersistence>(GetPersistenceImplementationName);

            IPersistence p = uc.Resolve<IPersistence>();
            p.Add(new Object());
        }
    }
}
